<?php
ob_start();
include("dbinfo.inc.php");
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database"); 

// get the trail ID from the DB using the name
$query="select ID from Trail where name like '$_POST[trailName]';";
$resultID=mysql_query($query);
if (!$resultID) {
  echo "Error selecting ID from Trail: " . mysql_error();
  die("");
}
$trailID=mysql_result($resultID,0, "ID");

// get the user ID from the DB using the name
$query="select ID from Account where userName like '$_POST[userName]';";
$resultID=mysql_query($query);
if (!$resultID) {
  echo "Error selecting ID from Account: " . mysql_error();
  die("");
}
$userID=mysql_result($resultID,0, "ID");

$query = "
INSERT INTO Review (trailID, userID, rating, review)
VALUES (
	$trailID,
	$userID,
	$_POST[rating],
	'$_POST[review]'
)";

if (!mysql_query($query)) {
  echo "Error inserting entry into Review: " . mysql_error();
}

//updating avg trail rating
$query="SELECT avg(rating) from Review where trailID=$trailID";
$resultRating=mysql_query($query);
if (!$resultRating) {
  echo "Error selecting avg: " . mysql_error();
}
$avgRating=mysql_result($resultRating,0, "avg(rating)");

$query=" UPDATE Trail SET avgRating=$avgRating WHERE ID=$trailID ";
if (!mysql_query($query)) {
  echo "Error updating avg: " . mysql_error();
}

mysql_close();
header("Location: index.php");
ob_flush();
?> 
